<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2005/08/07 05:20:29 $)
// $RCSfile: functions_template.php,v $ : $Revision: 1.16 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Rebuilds the Template Group assignments cache
*/
function rebuildTemplateGroupAssignCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$_cache = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tgroupassigns` ORDER BY `tgroupassignid` ASC;");
	while ($dbCore->nextRecord())
	{
		$_cache[$dbCore->Record["type"]][$dbCore->Record["toassignid"]][] = $dbCore->Record["tgroupid"];
	}

	$datastore->update("tgroupassigncache", $_cache);
}

/**
* Insert the Link for Template Group Assigns
*/
function insertTemplateGroupAssignLink($tgroupidlist, $type, $toassignid, $isupdate = false)
{
	global $dbCore;

	if ($isupdate == true)
	{
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."tgroupassigns` WHERE `toassignid` = '". intval($toassignid) ."' AND `type` = '". intval($type) ."';"); 
	}

	$assignsql = array();
	if (_is_array($tgroupidlist))
	{
		foreach ($tgroupidlist as $key=>$val)
		{
			$assignsql[] = "('". intval($toassignid) ."', '". intval($type) ."', '". intval($val) ."')";
		}

		if (count($assignsql))
		{
			$dbCore->query("INSERT INTO `". TABLE_PREFIX ."tgroupassigns` (`toassignid`, `type`, `tgroupid`) VALUES ". implode(",", $assignsql).";");
		}

		rebuildTemplateGroupAssignCache();
	}

	return true;
}

/**
* Delete the assign links
*/
function deleteTemplateGroupAssignLinks($toassignidlist, $type)
{
	global $dbCore;

	if (!_is_array($toassignidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."tgroupassigns` WHERE `toassignid` IN (". buildIN($toassignidlist) .") AND `type` = '". intval($type) ."';");

	rebuildTemplateGroupAssignCache();
}

/**
* Builds an option list for <SELECT> tag
*/
function buildTemplateGroupOptions($selectedgroup)
{
	global $_SWIFT, $dbCore, $datastore;

	$datastore->load("tgroupcache");

	if (!is_array($selectedgroup))
	{
		$selectedgroup = array("1");
	}
	
	foreach ($_SWIFT["tgroupcache"] as $key=>$val)
	{
		$retoptions .= '<option value="'. $val["tgroupid"] .'"'. iif(in_array($val["tgroupid"], $selectedgroup), " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
	}

	return $retoptions;
}

/**
* Rebuilds the template group cache
*/
function rebuildTemplateGroupCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$tgrouparray = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templategroups` ORDER BY `tgroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$tgrouparray[$dbCore->Record["tgroupid"]] = $dbCore->Record;
	}

	$datastore->update("tgroupcache", $tgrouparray);
}

/**
* Inserts a new template category for given template group
*/
function insertTemplateCategory($tgroupid, $name, $description, $module)
{
	global $dbCore;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templatecategories` (`tgroupid`, `name`, `description`, `module`) VALUES ('". intval($tgroupid) ."', '". $dbCore->escape($name) ."', '". $dbCore->escape($description) ."', '". $dbCore->escape($module) ."');", 3);
	
	$categoryid = $dbCore->lastInsertId();

	return $categoryid;
}

/**
* Insert a new template, DOES NOT insert the entry for templatedata
*/
function insertTemplate($tgroupid, $tcategoryid, $name, $templatelength, $modified, $contentshash, $contentsdefaulthash)
{
	global $dbCore;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templates` (`tgroupid`, `tcategoryid`, `name`, `templatelength`, `dateline`, `modified`, `contentshash`, `contentsdefaulthash`) VALUES('". intval($tgroupid) ."', '". $dbCore->escape($tcategoryid) ."', '". $dbCore->escape($name) ."', '". $dbCore->escape($templatelength) ."', '". time() ."', 'notmodified', '". $dbCore->escape($contentshash) ."', '". $dbCore->escape($contentsdefaulthash) ."');", 3);

	$templateid = $dbCore->lastInsertId();

	return $templateid;
}

/**
* Insert the given templatedata chunk sqls in steps of 10
*/
function insertTemplateDataChunks($contentssql)
{
	global $dbCore;

	// Insert all the template data in chunks of 10
	$sqlcount = count($contentssql);
	$insertedchunks = 0;
	if ($sqlcount)
	{
		$chunk = 10;
		$loopcount = ceil($sqlcount/$chunk);

		for ($ii=1; $ii<=$loopcount; $ii++)
		{
			$slicecontents = array();
			$slicelength = $ii*$chunk;
			$sliceoffset = ($slicelength-$chunk);
			if ($slicelength > $sqlcount)
			{
				$slicelength = $sqlcount;
			}
			$slicecontents = array_slice($contentssql, $sliceoffset, $slicelength);
			$slicechunks = count($slicecontents);
			$insertedchunks += count($slicecontents);
			$contentchunks = count($contentssql);
			if ($insertedchunks > $sqlcount)
			{
				$insertedchunks = $sqlcount;
				break;
			}

			$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templatedata` (`templateid`, `contents`, `contentsdefault`) VALUES ". implode(", ",$slicecontents).";", 5);
		}
	}

	if ($sqlcount != $insertedchunks)
	{
		return false;
	}

	return true;
}

/**
* Copies over all templates and categories from one group to another
*/
function copyTemplatesFromGroup($totgroupid, $fromtgroupid)
{
	global $dbCore, $_SWIFT;

	$contentssql = array();

	// Get all the categories from the group to copy from
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templatecategories` WHERE `tgroupid` = '". intval($fromtgroupid) ."';");
	while ($dbCore->nextRecord())
	{
		// Insert the same category for other group

		$categoryid = insertTemplateCategory($totgroupid, $dbCore->Record["name"], $dbCore->Record["description"], $dbCore->Record["module"]);

		// Iterate through all available templates for this category
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templates` AS templates LEFT JOIN `". TABLE_PREFIX ."templatedata` AS templatedata ON (templates.templateid = templatedata.templateid) WHERE templates.tcategoryid = '". intval($dbCore->Record["tcategoryid"]) ."';", 2);
		while ($dbCore->nextRecord(2))
		{
			$templateid = insertTemplate($totgroupid, $categoryid, $dbCore->Record2["name"], $dbCore->Record2["templatelength"], $dbCore->Record2["modified"], $dbCore->Record2["contentshash"], $dbCore->Record2["contentsdefaulthash"]);

			$contentssql[] = "('". intval($templateid) ."', '". $dbCore->escape($dbCore->Record2["contents"]) ."', '". $dbCore->escape($dbCore->Record2["contentsdefault"]) ."')";
//			echo "Inserting Template: ".$dbCore->Record2["name"].", Length: ". strlen($dbCore->Record2["contents"]) ."<BR />";
			if (count($contentssql) > 5)
			{
//				echo "Inserting Data1: ".$dbCore->Record2["name"]."<BR />";
				$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templatedata` (`templateid`, `contents`, `contentsdefault`) VALUES ". implode(", ",$contentssql).";", 5);
				unset($contentssql);
			}
		}
	}

	if (count($contentssql))
	{
//		print_r($contentssql);
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templatedata` (`templateid`, `contents`, `contentsdefault`) VALUES ". implode(", ",$contentssql).";", 5);
	}

	return true;
}

/**
* Insert a new template group
*/
function insertGroup($fromtgroupid, $guestusergroupid, $regusergroupid, $title, $description, $companyname, $grouppassword, $languageid, $restrictgroups, $isdefault, $loginapi_moduleid, $departmentid, $ticketstatusid, $priorityid)
{
	global $dbCore;

	// If we are setting this group as default then unset the default status for all other groups
	if ($isdefault == "1")
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."templategroups` SET `isdefault` = '0';");
	}

	// Insert the new template group
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templategroups` (`languageid`, `guestusergroupid`, `regusergroupid`, `title`, `description`, `companyname`, `ismaster`, `grouppassword`, `restrictgroups`, `isdefault`, `loginapi_moduleid`, `ticketstatusid`, `priorityid`, `departmentid`) VALUES ('". intval($languageid) ."', '". intval($guestusergroupid) ."', '". intval($regusergroupid) ."', '". $dbCore->escape(strtolower($title)) ."', '". $dbCore->escape($description) ."', '". $dbCore->escape($companyname) ."', '0', '". iif(trim($grouppassword)!="",md5($grouppassword)) ."', '". intval($restrictgroups) ."', '". iif($isdefault=="1", "1", "0") ."', '". $dbCore->escape($loginapi_moduleid) ."', '". intval($ticketstatusid) ."', '". intval($priorityid) ."', '". intval($departmentid) ."');");
	$tgroupid = $dbCore->lastInsertId();

	// Now that the group is created, copy all templates from the copy group to this one.
	copyTemplatesFromGroup($tgroupid, $fromtgroupid);

	// Rebuild the template group cache
	rebuildTemplateGroupCache();

	return $tgroupid;
}

/**
* Update an existing template group template group
*/
function updateGroup($tgroupid, $guestusergroupid, $regusergroupid, $title, $description, $companyname, $resetpw, $grouppassword, $languageid, $restrictgroups, $isdefault, $loginapi_moduleid, $departmentid, $ticketstatusid, $priorityid)
{
	global $dbCore;

	// If we are setting this group as default then unset the default status for all other groups
	if ($isdefault == "1")
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."templategroups` SET `isdefault` = '0';");
	}

	if ($resetpw == true)
	{
		$grouppwsql = ", `grouppassword` = '". iif(trim($grouppassword)!="",md5($grouppassword)) ."'";
	}

	// Update this group
	$dbCore->query("UPDATE `". TABLE_PREFIX ."templategroups` SET `languageid` = '". intval($languageid) ."', `guestusergroupid` = '". intval($guestusergroupid) ."', `regusergroupid` = '". intval($regusergroupid) ."', `title` = '". $dbCore->escape(strtolower($title)) ."', `description` = '". $dbCore->escape($description) ."', `companyname` = '". $dbCore->escape($companyname) ."'". $grouppwsql .", `restrictgroups` = '". intval($restrictgroups) ."', `isdefault` = '". iif($isdefault=="1", "1", "0") ."', `loginapi_moduleid` = '". $dbCore->escape($loginapi_moduleid) ."', `ticketstatusid` = '". intval($ticketstatusid) ."', `priorityid` = '". intval($priorityid) ."', `departmentid` = '". intval($departmentid) ."' WHERE `tgroupid` = '". intval($tgroupid) ."';");

	// Rebuild the template group cache
	rebuildTemplateGroupCache();

	return true;
}

/**
* Deletes the given template group
*/
function deleteGroups($tgroupidarray)
{
	global $dbCore;

	$resetdefault = false;

	if (!_is_array($tgroupidarray))
	{
		return false;
	}

	$dbCore->query("SELECT `tgroupid`, `isdefault`, `ismaster` FROM `". TABLE_PREFIX ."templategroups` WHERE `tgroupid` IN (". buildIN($tgroupidarray) .");");
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["isdefault"] == 1)
		{
			$resetdefault = true;
		}

		// Check to see if we are deleting a master group
		if (in_array($dbCore->Record["tgroupid"], $tgroupidarray) && $dbCore->Record["ismaster"] == "1")
		{
			// woops!.. no go.. nuke that value
			$newarray = array_flip($tgroupidarray);
			unset($newarray[$dbCore->Record["tgroupid"]]);
			$tgroupidarray = array_flip($newarray);
		}
	}

	$templateidlist = array();

	// Get the template ids for this group 
	$dbCore->query("SELECT `templateid` FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` IN (". buildIN($tgroupidarray) .");");
	while ($dbCore->nextRecord())
	{
		$templateidlist[] = $dbCore->Record["templateid"];
	}

	// First nuke all the template data
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."templatedata` WHERE `templateid` IN (". buildIN($templateidlist) .");");
	
	// Now nuke the templates
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` IN (". buildIN($tgroupidarray) .");");

	// Categories...
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."templatecategories` WHERE `tgroupid` IN (". buildIN($tgroupidarray) .");");

	// Actual group
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."templategroups` WHERE `tgroupid` IN (". buildIN($tgroupidarray) .");");

	// Reset the default group to a master group
	if ($resetdefault == true)
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."templategroups` SET `isdefault` = '1' WHERE `ismaster` = '1';");
	}

	rebuildTemplateGroupCache();
	
	return true;
}

/**
* Restores all template in the selected group to their original counterparts
*/
function restoreGroup($tgroupid)
{
	global $dbCore;

	$templateidlist = array();
	// First build the list of templates
	$dbCore->query("SELECT `templateid` FROM `". TABLE_PREFIX ."templates` WHERE `tgroupid` = '". intval($tgroupid) ."';");
	while ($dbCore->nextRecord())
	{
		$templateidlist[] = $dbCore->Record["templateid"];
	}

	// Now run the update query to update all templates
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."templatedata` SET `contents` = `contentsdefault` WHERE `templateid` IN (". buildIN($templateidlist) .");");

	// Update the modified status of all templates
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."templates` SET dateline = '". DATENOW ."', `modified` = '". MODIFIED_NONE ."' WHERE `templateid` IN (". buildIN($templateidlist) .");");
}

/**
* Returns the ID of the master group
*/
function getMasterGroupID()
{
	global $dbCore;

	$_result = $dbCore->queryFetch("SELECT `tgroupid` FROM `". TABLE_PREFIX ."templategroups` WHERE `ismaster` = '1';");

	if (!isset($_result["tgroupid"]))
	{
		return false;
	}

	return $_result["tgroupid"];
}

/**
* Update the given template with the $contents
*/
function updateTemplate($templateid, $contents)
{
	global $dbCore;

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."templates` SET `contentshash` = '". md5($contents) ."', `dateline` = '". DATENOW ."', `modified` = '". MODIFIED_USER ."', `templatelength` = '". strlen($contents) ."' WHERE `templateid` = '". intval($templateid) ."';");

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."templatedata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE `templateid` = '". intval($templateid) ."';");

	return true;
}

/**
* Restores the template to original contents
*/
function restoreTemplate($templateid)
{
	global $dbCore;

	$_template = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templates` AS templates LEFT JOIN `". TABLE_PREFIX ."templatedata` AS templatedata ON (templates.templateid = templatedata.templateid) WHERE templates.templateid = '". intval($templateid) ."';");
	if (empty($_template["templateid"]))
	{
		return false;
	}

	// Ok now update the db to original contents

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."templates` SET `contentshash` = '". md5($_template["contentsdefault"]) ."', `dateline` = '". DATENOW ."', `modified` = '". MODIFIED_NONE ."', `templatelength` = '". strlen($_template["contentsdefault"]) ."' WHERE `templateid` = '". intval($templateid) ."';");

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."templatedata` SET `contents` = `contentsdefault` WHERE `templateid` = '". intval($templateid) ."';");

	return true;	
}

/**
* Imports the templates from a file into the given template group
*/
function importTemplateFromFile($filename, $templategroupid, $versioncheck = false)
{
	global $_SETUP, $_SWIFT, $xml, $dbCore, $datastore;

	// Parse the templates XML File.
	$xmltemplates = $xml->xml2tree(implode("", file($filename)));
	$finaltemplates = &$xmltemplates["swifttemplate"][0]["children"];
	$title = $finaltemplates["title"][0]["values"][0];
	$author = $finaltemplates["author"][0]["values"][0];
	$version = $finaltemplates["version"][0]["values"][0];

	if (!empty($version) && $versioncheck == true)
	{
		// check for version
		if (version_compare($version, SWIFTVERSION) == -1)
		{
			return -1;
		}
	}
	
	if (empty($title))
	{
		return false;
	}

	$categorylist = $templatelist = $contentssql = $result = array();

	for ($ii=0; $ii<count($finaltemplates["category"]); $ii++)
	{
		// This is our attribute holder, contains the category name etc
		$category = &$finaltemplates["category"][$ii]["attrs"];
		$categoryid = array();
		$categorygroup = array();

		if (in_array($category["module"], $_SETUP["modules"]))
		{
			// Only proceed if the category module is in the allowed module list
			// Insert category for the given template group

			$currentcategoryid = insertTemplateCategory($templategroupid, $category["name"], $category["description"], $category["module"]);

			$categorylist[] = $category["name"];
			$categoryid[] = $currentcategoryid;

			$categorygroup[$currentcategoryid] = "1";

			// Now we iterate through individual templates for this category
			for ($kk=0; $kk<count($finaltemplates["category"][$ii]["children"]["template"]); $kk++)
			{
				$template = $finaltemplates["category"][$ii]["children"]["template"][$kk]["attrs"];
				$contents = $finaltemplates["category"][$ii]["children"]["template"][$kk]["values"][0];
				$contentshash = md5($contents);

				$templateid = insertTemplate($templategroupid, $currentcategoryid, $template["name"], strlen($contents), "notmodified", $contentshash, $contentshash);

				$templatelist[] = $template["name"];

				$contentssql[] = "('". intval($templateid) ."', '". $dbCore->escape($contents) ."', '". $dbCore->escape($contents) ."')";
				if (count($contentssql) >= 9)
				{
					insertTemplateDataChunks($contentssql);
					unset($contentssql);
				}
			}
		}
	}

	if (count($contentssql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."templatedata` (`templateid`, `contents`, `contentsdefault`) VALUES ". implode(", ",$contentssql).";", 5);
	}

	$result["categorylist"] = $categorylist;
	$result["templatelist"] = $templatelist;

	return $result;
}

/**
* Makes up the template file name using product name & version
*/
function generateTemplateFilename($grouptitle = "")
{
	return strtolower(SWIFTPRODUCT). ".". str_replace(".", "-", SWIFTVERSION) .iif(!empty($grouptitle), ".". strtolower(cleanVar($grouptitle))) .".templates.xml";
}

/**
* Exports the template xml file
*/
function doExportTemplate($tgroupid, $exportoptions, $filename = "")
{
	global $dbCore, $xml, $_SWIFT, $template;

	$categorylist = $categorydata = $templatelist = $templatedata = array();

	$_group = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templategroups` WHERE `tgroupid` = '". intval($tgroupid) ."';");
	if (empty($_group["tgroupid"]))
	{
		return false;
	}
	
	if (empty($filename))
	{
		$filename = generateTemplateFilename($_group["title"]);
	}

	if (function_exists("set_time_limit") && !ini_get("safe_mode"))
	{
		@set_time_limit(1500);
	}

	// ======= Fetch the group category data =======
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templatecategories` WHERE `tgroupid` = '". intval($tgroupid) ."';");
	while ($dbCore->nextRecord())
	{
		$categorydata[$dbCore->Record["tcategoryid"]] = $dbCore->Record;
		$categorylist[] = $dbCore->Record["tcategoryid"];
	}

	if ($exportoptions == EXPORT_ALL)
	{
		unset($modified);
	} else {
		$modified = " AND templates.modified = '". MODIFIED_USER ."'";
	}

	// ======= Fetch all the templates under the category =======
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templates` AS templates LEFT JOIN `". TABLE_PREFIX ."templatedata` AS templatedata ON (templates.templateid = templatedata.templateid) WHERE templates.tcategoryid IN (". buildIN($categorylist) .")". $modified .";");
	while ($dbCore->nextRecord())
	{
		$templatedata[$dbCore->Record["tcategoryid"]][] = $dbCore->Record;
	}

	// ======= Process all data into XML now =======
	$xml->addComment(sprintf($_SWIFT["language"]["generationdate"], edate($_SWIFT["settings"]["dt_datetimeformat"], DATENOW)));
	$xml->addParentTag("swifttemplate");
		$xml->addTag("title", $_group["title"]);
		$xml->addTag("author", $_group["companyname"]);
		$xml->addTag("version", SWIFTVERSION);

		foreach ($categorydata as $key=>$val)
		{
			if (_is_array($templatedata[$val["tcategoryid"]]))
			{
				$xml->addParentTag("category", array("name" => $val["name"], "module" => $val["module"]));
			
				// Now iterate through templates for this category
				foreach ($templatedata[$val["tcategoryid"]] as $templatekey=>$templateval)
				{
						$xml->addTag("template", $templateval["contents"], array("name" => $templateval["name"], "date" => $templateval["dateline"]));
				}

				$xml->endTag("category");
			}
		}
	$xml->endTag("swifttemplate");

	$xmldata = $xml->returnXML();


	if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
		// IE Bug in download name workaround
		ini_set( 'zlib.output_compression','Off' );
	}

	header("Content-Type: application/force-download");

	if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	} else{
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	}

	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ". strlen($xmldata));

	echo $xmldata;

	echo preg_replace("#(\r\n|\r|\n)#s", SWIFT_CRLF, $xmldata);
}

/**
* Import templates and create a new group
*/
function importCreateNewGroup($filename, $versioncheck = false)
{
	global $_SETUP, $_SWIFT, $xml, $dbCore, $datastore;

	// Parse the templates XML File.
	$xmltemplates = $xml->xml2tree(implode("", file($filename)));
	$finaltemplates = &$xmltemplates["swifttemplate"][0]["children"];
	$title = $finaltemplates["title"][0]["values"][0];
	$author = $finaltemplates["author"][0]["values"][0];
	$version = $finaltemplates["version"][0]["values"][0];

	if (!empty($version) && $versioncheck == true)
	{
		// check for version
		if (version_compare($version, SWIFTVERSION) == -1)
		{
			return -1;
		}
	}

	if (empty($title))
	{
		return -2;
	}

	// Get default group options
	$_templategroup = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templategroups` WHERE `ismaster` = '1';");

	// Get guest group
	$_guestusergroup = $dbCore->queryFetch("SELECT `usergroupid` FROM `". TABLE_PREFIX ."usergroups` WHERE `grouptype` = '". USERGROUP_GUEST ."' ORDER BY `usergroupid` ASC LIMIT 1;", 5);
	$_regusergroup = $dbCore->queryFetch("SELECT `usergroupid` FROM `". TABLE_PREFIX ."usergroups` WHERE `grouptype` = '". USERGROUP_REGISTERED ."' ORDER BY `usergroupid` ASC LIMIT 1;", 5);
	
	// First create a group with default options
	$tgroupid = insertGroup(1, $_guestusergroup["usergroupid"], $_regusergroup["usergroupid"], $title, "", $_templategroup["companyname"], "", 1, 0, 0, LOGINAPI_DEFAULT, 1, 1, 1);
	if (!$tgroupid)
	{
		return -2;
	}

	// Now when the template group is created with default templates, we import the ones from file.
	updateTemplatesFromFile($filename, $versioncheck);

	// All done, return the new tgroupid
	rebuildTemplateGroupCache();

	return $tgroupid;
}

/**
* Updates all template for upgrade system... I hate this function... took me frigging 2 hrs to write and debug.. I am sure you will hate it too
*/
function updateTemplatesFromFile($filename, $versioncheck = false, $templategrouprestrict = false)
{
	global $_SETUP, $_SWIFT, $xml, $dbCore, $datastore, $module;

	// Parse the templates XML File.
	$xmltemplates = $xml->xml2tree(implode("", file($filename)));
	$finaltemplates = &$xmltemplates["swifttemplate"][0]["children"];
	$title = $finaltemplates["title"][0]["values"][0];
	$author = $finaltemplates["author"][0]["values"][0];
	$version = $finaltemplates["version"][0]["values"][0];

	if (!empty($version) && $versioncheck == true)
	{
		// check for version
		if (version_compare($version, SWIFTVERSION) == -1)
		{
			return -1;
		}
	}

	if (function_exists("set_time_limit") && !ini_get("safe_mode"))
	{
		@set_time_limit(1500);
	}
	
	if (empty($title))
	{
		return false;
	}

	$categorylist = $templatelist = $contentssql = $result = $grouplist = array();

	// ======= Fetch All Template Groups =======
	$dbCore->query("SELECT `tgroupid`, `title` FROM `". TABLE_PREFIX ."templategroups` ORDER BY tgroupid ASC;", 5);
	while ($dbCore->nextRecord(5))
	{
		$grouplist[] = $dbCore->Record5;
	}

	if ($templategrouprestrict)
	{
		$grouplist = array($templategrouprestrict);
		$modifiedstatus = "user";
	} else {
		$modifiedstatus = "upgrade";
	}

	for ($ii=0; $ii<count($finaltemplates["category"]); $ii++)
	{
		// This is our attribute holder, contains the category name etc
		$category = &$finaltemplates["category"][$ii]["attrs"];
		$categoryid = $categorygroup = $templatehashlist = array();
		$proceed = false;

		if (_is_array($_SETUP["modules"]))
		{
			if (@in_array($category["module"], $_SETUP["modules"]))
			{
				$proceed = true;
			}
		} else {
			if ($module->isRegistered($category["module"]))
			{
				$proceed = true;
			}
		}

		if ($proceed)
		{
			// ======= Iterate through all the groups and look for categories =======
			foreach ($grouplist as $key=>$val)
			{
				$groupRecord = &$val;

				// Does this category exist for this template group?
				$catRecord = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templatecategories` WHERE `name` = '". addslashes($category["name"]) ."' AND `tgroupid` = '". addslashes($groupRecord["tgroupid"]) ."';");

				if ($catRecord["tgroupid"] == $groupRecord["tgroupid"])
				{
					// Exists
					$categoryid[] = $catRecord["tcategoryid"];
					$categorygroup[$catRecord["tcategoryid"]] = $catRecord["tgroupid"];
				} else {
					// Insert a new template category for this group as it doesnt exist
					$currentcategoryid = insertTemplateCategory($groupRecord["tgroupid"], $category["name"], $category["description"], $category["module"]);

					$categorylist[] = $category["name"];
					$categoryid[] = $currentcategoryid;
					$categorygroup[$currentcategoryid] = $groupRecord["tgroupid"];
				}
			}

			// ======= Build Content Hash for all Templates under this Category for ALL Groups =======
			$dbCore->query("SELECT `contentshash`, `templateid`, `name` FROM `". TABLE_PREFIX ."templates` WHERE `tcategoryid` IN (". buildIN($categoryid) .");", 5);
			while ($dbCore->nextRecord(5))
			{
				$index = count($templatehashlist[$dbCore->Record["name"]]);
				$templatehashlist[$dbCore->Record["name"]][$index]["contentshash"] = $dbCore->Record5["contentshash"];
				$templatehashlist[$dbCore->Record["name"]][$index]["templateid"] = $dbCore->Record5["templateid"];
			}

			// Now we iterate through individual templates for this category
			for ($kk=0; $kk<count($finaltemplates["category"][$ii]["children"]["template"]); $kk++)
			{
				$template = $finaltemplates["category"][$ii]["children"]["template"][$kk]["attrs"];
				$contents = $finaltemplates["category"][$ii]["children"]["template"][$kk]["values"][0];
				$contentshash = md5($contents);

				$Record = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."templates` WHERE `tcategoryid` IN (". buildIN($categoryid) .") AND `name` = '". addslashes($template["name"]) ."';");
				if ($Record["totalitems"] > 0)
				{
					// Records are already there for this template, see if this template needs any updating
					$dbCore->query("SELECT `templateid`, `contentshash`, `contentsdefaulthash` FROM `". TABLE_PREFIX ."templates` WHERE `tcategoryid` IN (". buildIN($categoryid) .") AND `name` = '". addslashes($template["name"]) ."';", 5);
					while ($dbCore->nextRecord(5))
					{
						$templateRecord = $dbCore->Record5;
						if ($templategrouprestrict)
						{
							$hashcheck = $templateRecord["contentshash"];
						} else {
							$hashcheck = $templateRecord["contentsdefaulthash"];
						}

						// Does the hash differ with the one from our latest set file?
						if (md5($contents) != $hashcheck)
						{
							if ($templategrouprestrict)
							{
								$addiquerytemplate = ", `contentshash` = '". md5($contents) ."'";
								$addiquerytemplatedata = "`contents` = '". addslashes($contents) ."'";
							} else {
								$addiquerytemplate = ", `contentsdefaulthash` = '". md5($contents) ."'";
								$addiquerytemplatedata = "`contentsdefault` = '". addslashes($contents) ."'";
							}

							// Yes, Update the record for this template, set the modified status to upgrade
							$dbCore->query("UPDATE `". TABLE_PREFIX ."templates` SET modified = '". $modifiedstatus ."', `dateline` = '". DATENOW ."'". $addiquerytemplate ." WHERE `templateid` = '". intval($templateRecord["templateid"]) ."';");

							$dbCore->query("UPDATE `". TABLE_PREFIX ."templatedata` SET ". $addiquerytemplatedata ." WHERE `templateid` = '". intval($templateRecord["templateid"]) ."';");
						}
					}
							
				} else {
					// No such record! Seems like a new template, insert it for all the categories for all groups
					foreach ($categoryid as $key=>$val)
					{
						$catid = $val;
		
						$templateid = insertTemplate($categorygroup[$catid], $catid, $template["name"], strlen($contents), "notmodified", $contentshash, $contentshash);
	
						$templatelist[] = $template["name"];

						$contentssql[] = "('". intval($templateid) ."', '". $dbCore->escape($contents) ."', '". $dbCore->escape($contents) ."')";
					}
				}
			}
		}
	}

	if (!insertTemplateDataChunks($contentssql))
	{
		return false;
	}

	$result["categorylist"] = $categorylist;
	$result["templatelist"] = $templatelist;

	return $result;
}

/**
* Renders the EDIT/INSERT Template Group Form
*/
function renderTemplateGroupForm($type)
{
	global $dbCore, $_SWIFT, $module;

	printFormStart();
	printMainTableHeader(iif($type==INSERT,$_SWIFT["language"]["inserttemplategroup"], $_SWIFT["language"]["edittemplategroup"]));

	// ======= GENERAL OPTIONS =======
	printDescRow($_SWIFT["language"]["generaloptions"]);
	printTextRow("title", $_SWIFT["language"]["tgrouptitle"], $_SWIFT["language"]["desc_tgrouptitle"], "text", $_POST["title"]);
	printTextRow("companyname", $_SWIFT["language"]["companyname"], $_SWIFT["language"]["desc_companyname"], "text", $_POST["companyname"]);

	if ($type == INSERT)
	{
		$options = array();
		$index = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templategroups` ORDER BY `title` ASC;", 5);
		while ($dbCore->nextRecord(5))
		{
			$options[$index]["title"] = $dbCore->Record5["title"];
			$options[$index]["value"] = $dbCore->Record5["tgroupid"];
			$index++;
		}
		printSelectRow("fromtgroupid", $_SWIFT["language"]["copyfrom"], $_SWIFT["language"]["desc_copyfrom"], $options);
	}

	printYesNoRow("isdefault", $_SWIFT["language"]["isdefault"], $_SWIFT["language"]["desc_isdefault"], false);

	$options = array();
	$index = 0;
	require_once ("./includes/LoginShare/loginshare.config.php");
	foreach ($_LOGINAPI as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $key;
		$index++;
	}
	printSelectRow("loginapi_moduleid", $_SWIFT["language"]["loginshare"], $_SWIFT["language"]["desc_loginshare"], $options);


	$options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languages` ORDER BY `title` ASC;", 5);
	while ($dbCore->nextRecord(5))
	{
		$options[$index]["title"] = $dbCore->Record5["title"];
		$options[$index]["value"] = $dbCore->Record5["languageid"];
		$index++;
	}
	printSelectRow("languageid", $_SWIFT["language"]["defaultlanguage"], $_SWIFT["language"]["desc_defaultlanguage"], $options);

	if ($module->isRegistered(MODULE_TICKETS))
	{
		$options = array();
		$index = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."departments` WHERE `departmentmodule` = '". MODULE_TICKETS ."' ORDER BY `title` ASC;", 5);
		while ($dbCore->nextRecord(5))
		{
			$options[$index]["title"] = $dbCore->Record5["title"];
			$options[$index]["value"] = $dbCore->Record5["departmentid"];
			$index++;
		}
		printSelectRow("departmentid", $_SWIFT["language"]["ticketdep"], $_SWIFT["language"]["desc_ticketdep"], $options);

		$options = array();
		$index = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketstatus` ORDER BY `displayorder` ASC;", 5);
		while ($dbCore->nextRecord(5))
		{
			$options[$index]["title"] = $dbCore->Record5["title"];
			$options[$index]["value"] = $dbCore->Record5["ticketstatusid"];
			$index++;
		}
		printSelectRow("ticketstatusid", $_SWIFT["language"]["ticketstatus"], $_SWIFT["language"]["desc_ticketstatus"], $options);

		$options = array();
		$index = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketpriorities` ORDER BY `displayorder` ASC;", 5);
		while ($dbCore->nextRecord(5))
		{
			$options[$index]["title"] = $dbCore->Record5["title"];
			$options[$index]["value"] = $dbCore->Record5["priorityid"];
			$index++;
		}
		printSelectRow("priorityid", $_SWIFT["language"]["ticketpriority"], $_SWIFT["language"]["desc_ticketpriority"], $options);		
	}


	// ======= USER GROUPS =======
	printDescRow($_SWIFT["language"]["usergroups"]);
	$options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroups` WHERE `grouptype` = '". USERGROUP_GUEST ."' ORDER BY `title` ASC;", 5);
	while ($dbCore->nextRecord(5))
	{
		$options[$index]["title"] = $dbCore->Record5["title"];
		$options[$index]["value"] = $dbCore->Record5["usergroupid"];
		$index++;
	}
	printSelectRow("guestusergroupid", $_SWIFT["language"]["guestusergroup"], $_SWIFT["language"]["desc_guestusergroup"], $options);

	$options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroups` WHERE `grouptype` = '". USERGROUP_REGISTERED ."' ORDER BY `title` ASC;", 5);
	while ($dbCore->nextRecord(5))
	{
		$options[$index]["title"] = $dbCore->Record5["title"];
		$options[$index]["value"] = $dbCore->Record5["usergroupid"];
		$index++;
	}
	printSelectRow("regusergroupid", $_SWIFT["language"]["regusergroup"], $_SWIFT["language"]["desc_regusergroup"], $options);

	printYesNoRow("restrictgroups", $_SWIFT["language"]["restrictgroups"], $_SWIFT["language"]["desc_restrictgroups"], false);

	// ======= PASSWORD =======
	printDescRow($_SWIFT["language"]["passwordprotection"]);
	printYesNoRow("enablepassword", $_SWIFT["language"]["enablepassword"], $_SWIFT["language"]["desc_enablepassword"], false);
	printTextRow("password", $_SWIFT["language"]["password"], $_SWIFT["language"]["desc_password"], "password", $_POST["password"], "20");
	printTextRow("passwordconfirm", $_SWIFT["language"]["passwordconfirm"], $_SWIFT["language"]["desc_passwordconfirm"], "password", $_POST["passwordconfirm"], "20");

	printSubmitRow(iif($type==INSERT,$_SWIFT["language"]["insert"],$_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT,"inserttemplategroup", "edittemplategroup"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("tgroupid", $_POST["tgroupid"]);
	}
	printFormEnd();
}


/**
* Impports all the templates into the db

function setup_importtemplates($silent = false, $upgrade = false)
{
	global $_SETUP, $_SWIFT, $xml, $dbCore, $datastore;

	// Parse the templates XML File.
	$xmltemplates = $xml->xml2tree(implode("", file(dirname(__FILE__)."/swift.templates.xml")));
	$finaltemplates = &$xmltemplates["swifttemplate"][0]["children"];
		
	for ($ii=0; $ii<count($finaltemplates["category"]); $ii++)
	{
		// This is our attribute holder, contains the category name etc
		$category = &$finaltemplates["category"][$ii]["attrs"];
		$categoryid = array();
		$categorygroup = array();

		if (in_array($category["module"], $_SETUP["modules"]))
		{
			// Only proceed if the category module is in the allowed module list

			if ($upgrade)
			{

				// No such category exists, it seems we added this later on. Iterate through existing template groups and add a new category for each one of them.
				$dbCore->query("SELECT tgroupid, title FROM `". TABLE_PREFIX ."templategroups` ORDER BY tgroupid ASC;", 5);
				$tgroups = array();
				while ($dbCore->nextRecord(5))
				{
					$groupRecord = $dbCore->Record5;

					// Does this category exist for this template group?
					$catRecord = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."templatecategories` WHERE `name` = '". addslashes($category["name"]) ."' AND `tgroupid` = '". addslashes($groupRecord["tgroupid"]) ."';");

					if ($catRecord["tgroupid"] == $groupRecord["tgroupid"])
					{
						// Exists
						$categoryid[] = $catRecord["tcategoryid"];
						$categorygroup[$catRecord["tcategoryid"]] = $catRecord["tgroupid"];
					} else {
						// Insert a new template category for this group as it doesnt exist
						$_SWIFT["query"]["insert"]["templatecategories"][] = "INSERT INTO `". TABLE_PREFIX ."templatecategories` (`name`, `description`, `tgroupid`) VALUES('". addslashes($category["name"]) ."', '". addslashes($category["description"]) ."', '". addslashes($groupRecord["tgroupid"]) ."');";
						execQuery("insert", "Creating Template Category: ".$category["name"] ." (Template Group: ". $groupRecord["title"] .")", $silent);
						$currentcategoryid = setup_dbinsertid();
						$categoryid[] = $currentcategoryid;
						$categorygroup[$currentcategoryid] = $groupRecord["tgroupid"];						
					}
				}
			} else {				
				// Insert category for the default template group

				$_SWIFT["query"]["insert"]["templatecategories"] = "INSERT INTO `". TABLE_PREFIX ."templatecategories` (`name`, `description`, `tgroupid`) VALUES('". addslashes($category["name"]) ."', '". addslashes($category["description"]) ."', '". addslashes("1") ."');";
				execQuery("insert", "Creating Template Category: ".$category["name"], $silent);

				$currentcategoryid = $dbCore->lastInsertId();
				$categoryid[] = $currentcategoryid;

				$categorygroup[$currentcategoryid] = "1";
			}

			// Now we iterate through individual templates for this category
			for ($kk=0; $kk<count($finaltemplates["category"][$ii]["children"]["template"]); $kk++)
			{
				$template = $finaltemplates["category"][$ii]["children"]["template"][$kk]["attrs"];
				$contents = $finaltemplates["category"][$ii]["children"]["template"][$kk]["values"][0];

				if ($upgrade)
				{
					$Record = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."templates` WHERE `tcategoryid` IN (". buildIN($categoryid) .") AND `name` = '". addslashes($template["name"]) ."';");
					if ($Record["totalitems"] > 0)
					{
						// Records are already there for this template, see if this template needs any updating
						$dbCore->query("SELECT `contentshash`, `templateid` FROM `". TABLE_PREFIX ."templates` WHERE `tcategoryid` IN (". buildIN($categoryid) .") AND `name` = '". addslashes($template["name"]) ."';", 5);
						while ($dbCore->nextRecord(5))
						{
							$templateRecord = $dbCore->Record5;

							// Does the hash differ with the one from our latest set file?
							if (md5($contents) != $templateRecord["contentshash"])
							{
								// Yes, Update the record for this template, set the modified status to upgrade
	
								$_SWIFT["query"]["update"]["templates"][] = "UPDATE `". TABLE_PREFIX ."templates` SET `contentsdefault` = '". addslashes($contents) ."', `contentshash` = '". md5($contents) ."', modified = '". "upgrade" ."' WHERE templateid = '". $templateRecord["templateid"] ."';";

							}
						}
								
					} else {
						// No such record! Seems like a new template, insert it for all the categories for all groups
						foreach ($categoryid as $key=>$val)
						{
							$catid = $val;
							$_SWIFT["query"]["insert"]["templates"][] = "INSERT INTO `". TABLE_PREFIX ."templates` (`tgroupid`, `tcategoryid`, `name`, `templatelength`, `dateline`, `contents`, `contentsdefault`, `contentshash`, `modified`) VALUES('". addslashes($categorygroup[$catid]) ."', '". addslashes($catid) ."', '". addslashes($template["name"]) ."', '". addslashes(strlen($contents)) ."', '". addslashes(time()) ."', '". addslashes($contents) ."', '". addslashes($contents) ."', '". md5($contents) ."', 'notmodified');";

						}
					}

				} else {
					$_SWIFT["query"]["insert"]["templates"][] = "INSERT INTO `". TABLE_PREFIX ."templates` (`tgroupid`, `tcategoryid`, `name`, `templatelength`, `dateline`, `contents`, `contentsdefault`, `contentshash`, `modified`) VALUES('". addslashes("1") ."', '". addslashes($categoryid[0]) ."', '". addslashes($template["name"]) ."', '". addslashes(strlen($contents)) ."', '". addslashes(time()) ."', '". addslashes($contents) ."', '". addslashes($contents) ."', '". md5($contents) ."', 'notmodified');";					
				}
			}

			execQuery("insert", "Inserting Templates Into: ".$category["name"], $silent);
			execQuery("update", "Updating Templates For: ".$category["name"], $silent);
		}
	}
}
*/
?>